<script lang="tsx">
import { computed, defineComponent, type PropType, ref, unref } from 'vue'
import { ElRadio, ElRadioGroup } from 'element-plus'
import { get, omit } from 'lodash-es'
import type { OptionsItem } from '../types/formItem'
import { useRuleFormItem } from '../common/useFormItem'
import type { Recordable } from '../types/form'
import { propTypes } from '@/types/propTypes'

export default defineComponent({
  name: 'RadioGroup',
  props: {
    //当前数参数
    options: {
      type: Array as PropType<OptionsItem[]>,
      default: () => [],
    },
    modelValue: {
      type: [String, Number, Boolean],
      default: '',
    },
    labelField: propTypes.string.def('label'),
    valueField: propTypes.string.def('value'),
  },
  emit: ['update:modelValue'],
  setup(props, { emit, attrs }) {
    const emitData = ref<any[]>([])
    const [state] = useRuleFormItem(props, 'modelValue', 'change', emitData)

    const getOptions = computed(() => {
      const { labelField, valueField, options } = props
      const optionArr = unref(options).reduce((prev, next: Recordable) => {
        if (next) {
          prev.push({
            ...omit(next, [labelField, valueField]),
            label: get(next, labelField),
            value: get(next, valueField),
          })
        }
        return prev
      }, [] as OptionsItem[])

      return optionArr
    })

    function handleChange(args: any) {
      emitData.value = args
      emit('update:modelValue', emitData.value)
    }
    function Radio() {
      return getOptions.value.map((e: any, index: number) => (
        <ElRadio {...attrs} value={e.value} key={index + e.value} disabled={e.disabled || false}>
          {e.label}
        </ElRadio>
      ))
    }
    return () => {
      return (
        <ElRadioGroup {...attrs} model-value={state.value} onChange={handleChange}>
          {Radio()}
        </ElRadioGroup>
      )
    }
  },
})
</script>
